package com.aigou.admin.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * OSS对象存储工具
 *
 * @Author: Hor
 * @Date: 2024/12/6 10:07
 * @Version: 1.0
 */
public class OssUtil {

    private static final String ENDPOINT = "http://oss-cn-wuhan-lr.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5t8M6FLWhtZQ51a9ggTH";
    private static final String ACCESS_KEY_SECRET = "Z9j4tRajGuaUa2fLSrSKUG9NAmFki7";
    private static final String BUCKET_NAME = "aigou6";
    //目录名
    private static final String DIR = "images";

    /**
     * 文件上传
     * @param inputStream 文件流
     * @param fileName 文件名
     */
    public static void upload(InputStream inputStream, String fileName){
        OSS oss = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        oss.putObject(BUCKET_NAME,DIR +"/"+ fileName,inputStream);
        oss.shutdown();
    }

    /**
     * 获得文件URL
     * @param fileName 文件名
     * @return 文件URL
     */
    public static String getUrl(String fileName){
        OSS oss = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        //设置过期时间
        LocalDateTime time = LocalDateTime.now().plusDays(100);
        Date expiration = Date.from(time.atZone( ZoneId.systemDefault()).toInstant());
        URL url = oss.generatePresignedUrl(BUCKET_NAME, DIR +"/"+ fileName, expiration);
        oss.shutdown();
        return url.toString();
    }

    /*
       public static void main(String[] args) throws FileNotFoundException {
           upload(new FileInputStream("D:\\Thaor\\Pictures\\Saved Pictures\\tx.jpg"),"tx.jpg");
           System.out.println(getUrl("tx.jpg"));
       }
     */

}
